<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/9/10
 * Time: 22:28
 * 收货地址
 */
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Address extends Api {
	
	/**
	 * 列表
	 */
	public function index(){
		$userId = $this->auth->id;
		
		$rows = Db::name('address')->alias('a')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area aa', 'a.area_id = aa.id', 'left')
			->where(['a.user_id' => $userId, 'a.status' => \app\common\model\Address::STATUS_NORMAL])
			->field('a.id, a.name, a.mobile, a.province_id, a.city_id, a.area_id, a.address, a.is_default, p.name as province, c.name as city, aa.name as area')
			->order(['a.is_default' => 'desc', 'a.update_time' => 'desc'])
			->select();
		
		$this->success('查询成功', $rows);
	}
	
	/**
	 * 添加、编辑
	 */
	public function edit() {
		$data = $this->request->post();
		$check = new \app\common\validate\Address();
		if(!$check->check($data)) {
			$this->error($check->getError());
		}
		
		$model = new \app\common\model\Address();
		$userId = $this->auth->id;
		$data['user_id'] = $userId;
		
		if($data['is_default'] == 1) {
			//这条为默认，把原来的更改为不是默认
			Db::name('address')
				->where(['user_id' => $userId])
				->update(['is_default' => 0]);
		}
		
		if($data['id']) {
			$res = $model->allowField(true)
				->save($data, ['id' => $data['id'], 'user_id' => $userId]);
		} else {
			$res = $model->isUpdate(false)
				->allowField(true)
				->save($data);
		}
		
		if($res !== false) {
			$this->success('保存成功');
		} else {
			$this->error('保存出错', $model->getError());
		}
	}
	
	/**
	 * 删除
	 */
	public function del(){
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$model = new \app\common\model\Address();
		$res = $model
			->save(['status' => $model::STATUS_DELETE],
				['id' => $id, 'user_id' => $this->auth->id]);
		
		if($res === false) {
			$this->error('删除出错');
		} else {
			$this->success('删除成功');
		}
	}
}
